<?php
declare (strict_types = 1);
namespace app\api\controller;

use think\Request;
use app\BaseController;
use think\facade\Db;
use think\exception\ValidateException;

use app\api\validate\{MyValidate, UsersValidate, FinValidate, AdminValidate};

use app\api\model\{Star, Users, Code, Admin, Cash, UserShop, FinanceRecord};

class MyController extends BaseController
{
    /**
	 * 客服电话
	 */
    public function cust_phone()
    {
        $system = getSystemVal();
        $this->success_back('ok', $system['cust_phone']);
    }

    /**
	 * 验证手机号
	 */
    public function checkPhone()
    {
        $data = input('post.');
        
        try{
            validate(UsersValidate::class)->scene('login')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $codeModel = new Code();

        $res = $codeModel->checkCode($data['phone'], $data['code']);

        if($res['code'] != 'ok'){
            $this->error_back($res['msg']);
        } 

        $this->success_back('ok');
    }

    /**
	 * 股东星级列表
	 */
    public function getStarList()
    {
        if(request()->isPost()){
            $starModel = new Star();
            $list = $starModel->getList([], 0);

            if($list['data']->isEmpty()){
                $this->error_back('暂无数据');
            }

            $this->success_back('ok', $list['data']);
        }
    }

    /**
	 * 获取用户信息
	 */
    public function getUserInfo()
    {
        if(request()->isPost()){
            $data = input('post.');

            $userModel = new Users();

            $info = $userModel->getUserInfo(['id' => $data['user_id']]);

            $this->success_back('ok', $info);
        }
    }

    /**
	 * 绑定银行卡
	 */
    public function setBank()
    {
        if(request()->isPost()){
            $data = input('post.');

            try{
                validate(UsersValidate::class)->scene('bank')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }
    
            $usersModel = new Users();
            
            $data['id'] = $data['user_id'];
            $flag = $usersModel->edit($data, ['id', 'bank_number', 'bank_name', 'real_name']);
    
            if($flag['code'] != 'ok'){
                $this->error_back($flag['msg']);
            } 
    
            $this->success_back('ok');
        }
    }

    /**
	 * 绑定店主身份
	 */
    public function bindShop()
    {
        if(request()->isPost()){
            $data = input('post.');

            try{
                validate(UsersValidate::class)->scene('bind_shop')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }
    
            $usersModel = new Users();
            $adminModel = new Admin();

            $adminInfo = $adminModel->getFind(['username' => $data['username'], 'password' => setPass($data['password'])]);

            if($adminInfo['code'] != 'ok'){
                $this->error_back('店主管理账号或密码错误');
            }

            $userInfo = $usersModel->getFind(['id' => $data['user_id']]);

            if($userInfo['code'] != 'ok'){
                $this->error_back('该用户不存在');
            }
            
            $editData = [
                'id'       => $data['user_id'],
                'admin_id' => $userInfo['data']['bind_admin_id'],
                'type'     => 3,
            ];

            $flag = $usersModel->edit($editData, ['id', 'admin_id', 'type']);
    
            if($flag['code'] != 'ok'){
                $this->error_back($flag['msg']);
            } 
    
            $this->success_back('ok');
        }
    }

    /**
	 * 申请提现
	 */
    public function setCash()
    {
        if(request()->isPost()){
            $data = input('post.');

            try{
                validate(UsersValidate::class)->scene('cash')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }
    
            $usersModel = new Users();
            $cashModel  = new Cash();
            $userShopModel  = new UserShop();

            // 获取系统参数
            $system = getSystemVal();

            // 获取用户信息
            $userInfo = $usersModel->getUserInfo(['id' => $data['user_id']]);

            // 提现门槛判断
            if($system['cash_number'] > $userInfo['user_shop']['money']){
                $this->error_back('余额不足（少于' . $system['cash_number'] . '不能提现）');
            }

            // 收款信息判断
            if(!empty($userInfo['cash_number'])
                && !empty($userInfo['cash_name'])
                && !empty($userInfo['real_name'])
            ){
                $this->error_back('请完善银行卡信息');
            }
            
            // 开启事务
            Db::startTrans();

            try{
                $addData = [
                    'user_id'     => $data['user_id'],
                    'admin_id'    => $userInfo['bind_admin_id'],
                    'number'      => $data['number'],
                    'user_type'   => $userInfo['type'],
                    'bank_number' => $userInfo['bank_number'],
                    'bank_name'   => $userInfo['bank_name'],
                    'real_name'   => $userInfo['real_name'],
                ];
    
                $flag = $cashModel->add($addData);
        
                if($flag['code'] != 'ok'){
                    $this->error_back($flag['msg']);
                }

                // 用户减去对应佣金
                $userShopModel->setDecField(['user_id' => $data['user_id'], 'admin_id' => $userInfo['bind_admin_id']], 'money', $data['number']);

                // 写入财务记录
                addFin($data['user_id'], $userInfo['bind_admin_id'], $flag['data'], 4, 1, '-' . $data['number'], '提现');

                // 提交事务
                Db::commit();
            }catch(\Exception $e){
                // 回滚事务
                Db::rollback();
            }
    
            $this->success_back('ok');
        }
    }

    /**
	 * 我的好友
	 */
    public function getUserLine()
    {
        if(request()->isPost()){
            $data = input('post.');

            try{
                validate(UsersValidate::class)->scene('line')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $userModel = new Users();
            $userShopModel = new UserShop();

            /** 好友数 */
            $line_num = $userModel->getNum(['pid' => $data['user_id']]);

            /** 好友未购买数 */
            if($line_num['code'] != 'ok'){
                $no_buy = 0;
            }else{
                $no_buy = $line_num['data'];
            }

            /** 好友列表 */
            $list = $userModel->getList(['pid' => $data['user_id']], 1, $data['curr'], $data['limit']);

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            $user_list = [];
            foreach($list['data'] as $k => $v){
                $user_shop_info = $userShopModel->getFind(['user_id' => $v['id']]);

                if($user_shop_info['code'] != 'ok'){
                    unset($list['data'][$k]);
                    continue;
                }

                $user_info = [
                    'id'          => $v['id'],
                    'phone'       => $v['phone'],
                    'head_img'    => $v['head_img'],
                    'consume'     => $user_shop_info['data']['money_total'],
                    'star'        => $user_shop_info['data']['star_id'],
                    'create_time' => $user_shop_info['data']['create_time'],
                ];

                $no_buy = $no_buy - (int)$user_shop_info['data']['is_buy'];
                $user_list[] = $user_info;
            }

            $backData = [
                'line_num' => $line_num['data'],
                'no_buy'   => $no_buy,
                'list'     => $user_list
            ];

            $this->success_back('ok', $backData);
        }
    }

    /**
	 * 钱包明细
	 */
    public function wallet_details()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(FinValidate::class)->scene('money_list')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $finModel = new FinanceRecord();

            $field = ['id', 'content', 'number', 'create_time'];
            $where = ['user_id' => $data['user_id'], 'admin_id' => $data['admin_id'], 'money_type' => 1];
            $list = $finModel->getList($where, 1, $data['curr'], $data['limit'], $field, 'id DESC');

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            $this->success_back('ok', $list['data']);
        }
    }

    /**
	 * 门店合伙人数据
	 */
    public function getStarMoney()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(FinValidate::class)->scene('money_data')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $userShopModel = new UserShop();
            $finModel = new FinanceRecord();

            /** 查询用户资产信息 */
            $user_shop_info = $userShopModel->getFind(['user_id' => $data['user_id'], 'admin_id' => $data['admin_id']]);

            if($user_shop_info['code'] != 'ok'){
                $this->error_back('系统错误，请重新打开小程序');
            }

            /** 累计佣金收益 */
            $user_money_total = $finModel->where(['user_id' => $data['user_id'], 'admin_id' => $data['admin_id'], 'money_type' => 1])->sum('number');

            $back_data = [
                'money_total'    => $user_money_total,  /** 累计拥挤收益 */
                'money'          => $user_shop_info['data']['money'], /** 未提现收益 */
                'order_yesterday' => 0,  /** 昨日下级订单笔数 */
                'order_today'    => 0,  /** 今日下级订单笔数 */
                'money_yesterday' => 0,  /** 昨日预估佣金 */
                'money_today'    => 0,  /** 今日预估佣金 */
            ];

            $back_data['order_yesterday'] = $finModel->where(['user_id' => $data['user_id'], 'admin_id' => $data['admin_id'], 'money_type' => 1])->whereTime('create_time', 'yesterday')->count();
            $back_data['order_today'] = $finModel->where(['user_id' => $data['user_id'], 'admin_id' => $data['admin_id'], 'money_type' => 1])->whereTime('create_time', 'today')->count();

            $back_data['money_yesterday'] = $finModel->where(['user_id' => $data['user_id'], 'admin_id' => $data['admin_id'], 'money_type' => 1])->whereTime('create_time', 'yesterday')->sum('number');
            $back_data['money_today'] = $finModel->where(['user_id' => $data['user_id'], 'admin_id' => $data['admin_id'], 'money_type' => 1])->whereTime('create_time', 'today')->sum('number');

            $this->success_back('ok', $back_data);
        }
    }

    /**
	 * 获取店铺新人体验金
	 */
    public function getShopMoneyGold()
    {
        $data = input('post.');
        
        try{
            validate(AdminValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $adminModel = new Admin();

        $money = $adminModel->getVal(['id' => $data['admin_id']], 'money_gold');

        if($money['code'] != 'ok'){
            $this->error_back($money['msg']);
        } 

        $this->success_back('ok', $money['data']);
    }
}